package org.vergil.core.thread.productionmessage;

import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;

/**
 * Created by vergil on 17-3-18.
 */
@Service
public class Business {
    private BlockingQueue<Map<String,Object>> queue = new LinkedBlockingDeque<>(100);
    private BlockingQueue<Map<String,Object>> recordQueue = new LinkedBlockingDeque<>(100);
    private int count;

    public void push(List<Map<String,Object>> product) throws InterruptedException {
        for (Map<String, Object> map : product){
            queue.put(map);
            System.out.println("Producer put " + map.get("id"));
        }
        System.out.println("set after queue size is " + queue.size());
    }

    public Map<String,Object> getProduct() throws InterruptedException {
        Map<String, Object> result = queue.take();
        System.out.println("Consumer take " + result.get("id"));
        Map<String, Object> record = new HashMap<>();
        record.put("id",result.get("id"));
        record.put("time", LocalDateTime.now());
        recordQueue.put(record);
        return result;
    }

    public List<Map<String,Object>> getProducts(int num) throws InterruptedException {
        List<Map<String,Object>> products = new ArrayList<>();
        for (int i = 0; i <= num; i++) {
            products.add(getProduct());
        }
        System.out.println("get after queue size is " + queue.size());
        return products;
    }

    public BlockingQueue<Map<String,Object>> getQueue() {
        return queue;
    }

    public Map<String,Object> getRecord(){
         try {
            Map<String, Object> result = recordQueue.take();
            System.out.println("recordQueue put " + result.get("id"));
            count = Integer.parseInt(result.get("id").toString());
            return result;
        } catch (InterruptedException e) {
            return null;
        }
    }
}
